import { history } from 'umi'
import { fakeAccountLogin, logoutAdmin } from '@/services/login'
import { message } from 'antd'

const Model = {
  namespace: 'login',
  state: {
    status: undefined,
  },
  effects: {
    * login ({ payload }, { call, put }) {
      // 发送请求并且执行登录
      const response = yield call(fakeAccountLogin, payload)
      // 根据状态码 看是否登录成功
      if (response.status === undefined) {
        message.success('登录成功')
        yield put({
          type: 'changeLoginStatus',
          payload: response,
        }) // Login successfully

        history.replace('/')
      }
    },

    * logout (_, { call }) {
      const hide = message.loading('...退出中')
      //执行退出
      const response = yield call(logoutAdmin)
      //退出成功之后,清除token 和userinfo
      if (response.status === undefined) {
        localStorage.removeItem('access_token')
        localStorage.removeItem('adminInfo')
        message.success('退出成功')
        history.replace('/login')
      }
      setTimeout(hide, 300)
    },
  },
  reducers: {
    changeLoginStatus (state, { payload }) {
      // 将token存在localStorage中
      // setAuthority(payload.currentAuthority);
      let {access_token} = payload
      localStorage.setItem('access_token', access_token)
      return { ...state, status: payload.status, type: payload.type }
    },
  },
}
export default Model
